package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("用户名：{}", s);

        //判断有没有找到该用户的数据
        AdminLoginInfoVO loginInfoByUsername = adminMapper.getLoginInfoByUsername(s);
        if (loginInfoByUsername == null) {
            log.debug("没有找到该用户数据！");
            return null;
        }

        //找到了，将权限放进集合里
        log.debug("找到该用户数据，开始返回给security");
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = loginInfoByUsername.getPermissions();
        for (String value : permissions
        ) {
            GrantedAuthority authority = new SimpleGrantedAuthority(value);
            authorities.add(authority);
        }

        //new AdminDetails 设置参数 开始返回
        UserDetails userDetails = new AdminDetails(loginInfoByUsername.getId(),loginInfoByUsername.getUsername(), loginInfoByUsername.getPassword(), loginInfoByUsername.getEnable() == 1, authorities);
//        UserDetails userDetails = User.builder()
//                .username(loginInfoByUsername.getUsername())
//                .password(loginInfoByUsername.getPassword())
//                .disabled(loginInfoByUsername.getEnable() == 0)
//                .accountLocked(false)
//                .accountExpired(false)
//                .credentialsExpired(false)
//                .authorities("这是一个伪造的授权")
//                .build();
        return userDetails;
    }
}
